<template>
  <div class="finance-container">
    <div class="page-header">
      <div class="page-title">收支记录管理</div>
      <el-button type="primary" @click="handleAdd">添加记录</el-button>
    </div>

    <!-- 统计卡片 -->
    <div class="stat-cards">
      <el-card class="stat-card">
        <div class="stat-title">本月收入</div>
        <div class="stat-value income">{{ statData.monthIncome || 0 }} 元</div>
      </el-card>
      <el-card class="stat-card">
        <div class="stat-title">本月支出</div>
        <div class="stat-value expense">{{ statData.monthExpense || 0 }} 元</div>
      </el-card>
      <el-card class="stat-card">
        <div class="stat-title">本月结余</div>
        <div class="stat-value" :class="statData.monthBalance >= 0 ? 'income' : 'expense'">
          {{ statData.monthBalance || 0 }} 元
        </div>
      </el-card>
    </div>

    <!-- 统计图表 -->
    <el-row :gutter="20" class="chart-container">
      <el-col :span="12">
        <el-card class="chart-card">
          <div slot="header">收支趋势</div>
          <div ref="trendChart" class="chart"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="chart-card">
          <div slot="header">分类占比</div>
          <div ref="categoryChart" class="chart"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 搜索表单 -->
    <el-form :inline="true" :model="searchForm" class="search-form">
      <el-form-item label="标题">
        <el-input v-model="searchForm.title" placeholder="请输入标题" clearable />
      </el-form-item>
      <el-form-item label="类型">
        <el-select v-model="searchForm.type" placeholder="请选择类型" clearable>
          <el-option label="收入" value="INCOME" />
          <el-option label="支出" value="EXPENSE" />
        </el-select>
      </el-form-item>
      <el-form-item label="分类">
        <el-input v-model="searchForm.category" placeholder="请输入分类" clearable />
      </el-form-item>
      <el-form-item label="日期范围">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="financeList" border class="table-container">
      <el-table-column prop="title" label="标题" width="180" />
      <el-table-column prop="amount" label="金额" width="120">
        <template slot-scope="scope">
          <span :class="scope.row.type === 'INCOME' ? 'income' : 'expense'">
            {{ scope.row.type === 'INCOME' ? '+' : '-' }} {{ scope.row.amount }} 元
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="type" label="类型" width="100">
        <template slot-scope="scope">
          <el-tag :type="scope.row.type === 'INCOME' ? 'success' : 'danger'">
            {{ scope.row.type === 'INCOME' ? '收入' : '支出' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="category" label="分类" width="120" />
      <el-table-column prop="recordDate" label="记录日期" width="120" />
      <el-table-column prop="remark" label="备注" show-overflow-tooltip />
      <el-table-column label="操作" width="200" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="handleView(scope.row)">查看</el-button>
          <el-button size="mini" type="success" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :current-page.sync="pagination.pageNum"
        :page-sizes="[10, 20, 50, 100]"
        :page-size.sync="pagination.pageSize"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px" @closed="resetForm">
      <el-form ref="financeForm" :model="financeForm" :rules="financeRules" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="financeForm.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="金额" prop="amount">
          <el-input-number v-model="financeForm.amount" :precision="2" :step="10" :min="0" style="width: 100%" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-radio-group v-model="financeForm.type">
            <el-radio label="INCOME">收入</el-radio>
            <el-radio label="EXPENSE">支出</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-input v-model="financeForm.category" placeholder="请输入分类" />
        </el-form-item>
        <el-form-item label="记录日期" prop="recordDate">
          <el-date-picker
            v-model="financeForm.recordDate"
            type="date"
            placeholder="选择日期"
            style="width: 100%"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="financeForm.remark" type="textarea" :rows="3" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>

    <!-- 查看对话框 -->
    <el-dialog title="收支记录详情" :visible.sync="viewDialogVisible" width="500px">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="标题">{{ financeDetail.title }}</el-descriptions-item>
        <el-descriptions-item label="金额">
          <span :class="financeDetail.type === 'INCOME' ? 'income' : 'expense'">
            {{ financeDetail.type === 'INCOME' ? '+' : '-' }} {{ financeDetail.amount }} 元
          </span>
        </el-descriptions-item>
        <el-descriptions-item label="类型">
          <el-tag :type="financeDetail.type === 'INCOME' ? 'success' : 'danger'">
            {{ financeDetail.type === 'INCOME' ? '收入' : '支出' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="分类">{{ financeDetail.category || '-' }}</el-descriptions-item>
        <el-descriptions-item label="记录日期">{{ financeDetail.recordDate }}</el-descriptions-item>
        <el-descriptions-item label="备注">{{ financeDetail.remark || '-' }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script>
import { getFinanceList, addFinance, updateFinance, deleteFinance, getFinanceDetail, getFinanceStat, getFinanceStatByCategory } from '@/api/finance'
import * as echarts from 'echarts/lib/echarts'
import 'echarts/lib/chart/line'
import 'echarts/lib/chart/pie'
import 'echarts/lib/component/tooltip'
import 'echarts/lib/component/title'
import 'echarts/lib/component/legend'

export default {
  name: 'Finance',
  data() {
    return {
      // 搜索表单
      searchForm: {
        title: '',
        type: '',
        category: '',
        startDate: '',
        endDate: ''
      },
      dateRange: [],
      // 分页
      pagination: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      // 收支记录列表
      financeList: [],
      // 加载状态
      loading: false,
      // 对话框
      dialogVisible: false,
      dialogTitle: '添加收支记录',
      submitLoading: false,
      // 表单
      financeForm: {
        id: null,
        title: '',
        amount: 0,
        type: 'EXPENSE',
        category: '',
        recordDate: new Date().toISOString().split('T')[0],
        remark: ''
      },
      // 表单校验规则
      financeRules: {
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        amount: [{ required: true, message: '请输入金额', trigger: 'blur' }],
        type: [{ required: true, message: '请选择类型', trigger: 'change' }],
        category: [{ required: true, message: '请输入分类', trigger: 'blur' }],
        recordDate: [{ required: true, message: '请选择记录日期', trigger: 'change' }]
      },
      // 查看对话框
      viewDialogVisible: false,
      financeDetail: {},
      // 统计数据
      statData: {
        monthIncome: 0,
        monthExpense: 0,
        monthBalance: 0
      },
      // 图表实例
      trendChart: null,
      categoryChart: null
    }
  },
  watch: {
    dateRange(val) {
      if (val) {
        this.searchForm.startDate = val[0]
        this.searchForm.endDate = val[1]
      } else {
        this.searchForm.startDate = ''
        this.searchForm.endDate = ''
      }
    }
  },
  mounted() {
    this.fetchData()
    this.fetchStatData()
    this.initCharts()
  },
  methods: {
    // 获取收支记录列表
    fetchData() {
      this.loading = true
      getFinanceList({
        pageNum: this.pagination.pageNum,
        pageSize: this.pagination.pageSize,
        title: this.searchForm.title,
        type: this.searchForm.type,
        category: this.searchForm.category,
        startDate: this.searchForm.startDate,
        endDate: this.searchForm.endDate
      })
        .then(response => {
          const { data } = response
          this.financeList = data.records
          this.pagination.total = data.total
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },
    // 获取统计数据
    fetchStatData() {
      getFinanceStat()
        .then(response => {
          this.statData = response.data
          this.updateTrendChart()
        })
      
      getFinanceStatByCategory()
        .then(response => {
          this.updateCategoryChart(response.data)
        })
    },
    // 初始化图表
    initCharts() {
      this.$nextTick(() => {
        this.trendChart = echarts.init(this.$refs.trendChart)
        this.categoryChart = echarts.init(this.$refs.categoryChart)
        
        window.addEventListener('resize', () => {
          this.trendChart && this.trendChart.resize()
          this.categoryChart && this.categoryChart.resize()
        })
      })
    },
    // 更新趋势图表
    updateTrendChart() {
      // 这里使用模拟数据，实际应该从API获取
      const months = ['1月', '2月', '3月', '4月', '5月', '6月']
      const incomeData = [1000, 1200, 900, 1500, 2000, 1800]
      const expenseData = [800, 950, 1100, 1300, 1400, 1200]
      
      const option = {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['收入', '支出']
        },
        xAxis: {
          type: 'category',
          data: months
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '收入',
            type: 'line',
            data: incomeData,
            itemStyle: {
              color: '#67C23A'
            }
          },
          {
            name: '支出',
            type: 'line',
            data: expenseData,
            itemStyle: {
              color: '#F56C6C'
            }
          }
        ]
      }
      
      this.trendChart.setOption(option)
    },
    // 更新分类图表
    updateCategoryChart(data) {
      // 这里使用模拟数据，实际应该从API获取
      const pieData = [
        { name: '餐饮', value: 1200 },
        { name: '交通', value: 800 },
        { name: '购物', value: 600 },
        { name: '娱乐', value: 400 },
        { name: '其他', value: 300 }
      ]
      
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          right: 10,
          top: 'center',
          data: pieData.map(item => item.name)
        },
        series: [
          {
            name: '支出分类',
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '16',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: pieData
          }
        ]
      }
      
      this.categoryChart.setOption(option)
    },
    // 搜索
    handleSearch() {
      this.pagination.pageNum = 1
      this.fetchData()
    },
    // 重置搜索
    resetSearch() {
      this.searchForm = {
        title: '',
        type: '',
        category: '',
        startDate: '',
        endDate: ''
      }
      this.dateRange = []
      this.handleSearch()
    },
    // 分页大小变化
    handleSizeChange() {
      this.fetchData()
    },
    // 页码变化
    handleCurrentChange() {
      this.fetchData()
    },
    // 添加记录
    handleAdd() {
      this.dialogTitle = '添加收支记录'
      this.financeForm = {
        id: null,
        title: '',
        amount: 0,
        type: 'EXPENSE',
        category: '',
        recordDate: new Date().toISOString().split('T')[0],
        remark: ''
      }
      this.dialogVisible = true
    },
    // 查看记录
    handleView(row) {
      this.viewDialogVisible = true
      getFinanceDetail(row.id)
        .then(response => {
          this.financeDetail = response.data
        })
    },
    // 编辑记录
    handleEdit(row) {
      this.dialogTitle = '编辑收支记录'
      getFinanceDetail(row.id)
        .then(response => {
          this.financeForm = { ...response.data }
          this.dialogVisible = true
        })
    },
    // 删除记录
    handleDelete(row) {
      this.$confirm('确认删除该收支记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteFinance(row.id)
            .then(() => {
              this.$message({
                type: 'success',
                message: '删除成功'
              })
              this.fetchData()
              this.fetchStatData()
            })
        })
        .catch(() => {})
    },
    // 提交表单
    submitForm() {
      this.$refs.financeForm.validate(valid => {
        if (valid) {
          this.submitLoading = true
          if (this.financeForm.id) {
            // 更新
            updateFinance(this.financeForm)
              .then(() => {
                this.$message({
                  type: 'success',
                  message: '更新成功'
                })
                this.dialogVisible = false
                this.fetchData()
                this.fetchStatData()
                this.submitLoading = false
              })
              .catch(() => {
                this.submitLoading = false
              })
          } else {
            // 添加
            addFinance(this.financeForm)
              .then(() => {
                this.$message({
                  type: 'success',
                  message: '添加成功'
                })
                this.dialogVisible = false
                this.fetchData()
                this.fetchStatData()
                this.submitLoading = false
              })
              .catch(() => {
                this.submitLoading = false
              })
          }
        }
      })
    },
    // 重置表单
    resetForm() {
      if (this.$refs.financeForm) {
        this.$refs.financeForm.resetFields()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.finance-container {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
  }
  
  .stat-cards {
    display: flex;
    margin-bottom: 20px;
    
    .stat-card {
      flex: 1;
      margin-right: 20px;
      
      &:last-child {
        margin-right: 0;
      }
      
      .stat-title {
        font-size: 14px;
        color: #909399;
      }
      
      .stat-value {
        font-size: 24px;
        font-weight: bold;
        margin-top: 10px;
        
        &.income {
          color: #67C23A;
        }
        
        &.expense {
          color: #F56C6C;
        }
      }
    }
  }
  
  .chart-container {
    margin-bottom: 20px;
    
    .chart-card {
      height: 100%;
      
      .chart {
        height: 300px;
      }
    }
  }
  
  .income {
    color: #67C23A;
  }
  
  .expense {
    color: #F56C6C;
  }
  
  .search-form {
    margin-bottom: 20px;
  }
}
</style> 